package cn.practice.chat.handler;

import cn.practice.chat.lang.Result;
import cn.practice.chat.record.WsRecord;
import cn.practice.chat.utils.AnalysisUtil;
import cn.practice.chat.utils.JwtUtils;
import cn.practice.chat.utils.SpringContextUtil;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @ClassName ws鉴权
 * @Description:
 * @Author A-TAO
 * @Date 2022/10/31
 * @Version V1.0
 **/
@Slf4j
public class AuthTokenHandler  extends SimpleChannelInboundHandler<FullHttpRequest> {


    JwtUtils jwtUtils;
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
        String uri = fullHttpRequest.uri();
        log.info("url = {}", uri);
        jwtUtils = SpringContextUtil.getBean(JwtUtils.class);
        if(uri.contains("/ws")){
            int dex = uri.indexOf("?");
            String token = uri.substring(dex+1);
            //WsRecord wsRecord = AnalysisUtil.stringAnalysis(params, WsRecord.class);
            Result result = new Result();
            if(StringUtils.isEmpty(token)){
                // 验证失败
                result.setCode(401);
                result.setMsg("未获取到token");
                ctx.channel().writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(result)));
                ctx.close();
            }else {
                // 验证token正确性
                Claims claims = jwtUtils.getClaimByToken(token);
                if(ObjectUtils.isEmpty(claims) || jwtUtils.isTokenExpired(claims)){
                    result.setCode(401);
                    result.setMsg("token已经失效");
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(JSONObject.toJSON(result).toString()));
                    ctx.close();

                }else {
                    // token验证通过交给其他handler
                    ctx.fireChannelRead(fullHttpRequest.setUri(uri).retain());
                }
            }
        }else {
            ctx.fireChannelRead(fullHttpRequest.setUri(uri).retain());
        }

    }

}
